//
//  MakeSureToViewController.m
//  SP2P
//
//  Created by Eternal on 2017/8/23.
//  Copyright © 2017年 EIMS. All rights reserved.
//

#import "MakeSureToViewController.h"
#import "UILabel+attributeTextAction.h"
#import "RechargeVerifyViewController.h"
#import <FUMobilePay/FUMobilePay.h>
@interface MakeSureToViewController ()<HTTPClientDelegate,UIAlertViewDelegate>

@property (weak, nonatomic) IBOutlet UILabel *makeSure_name;
@property (weak, nonatomic) IBOutlet UILabel *makeSure_nameValue;
@property (weak, nonatomic) IBOutlet UILabel *makeSure_time;
@property (weak, nonatomic) IBOutlet UILabel *makeSure_timeValue;
@property (weak, nonatomic) IBOutlet UILabel *makeSure_payStyle;
@property (weak, nonatomic) IBOutlet UIImageView *payStyleImageView;
@property (weak, nonatomic) IBOutlet UILabel *bankStyleLab;
@property (weak, nonatomic) IBOutlet UILabel *bankNumLab;
@property (weak, nonatomic) IBOutlet UILabel *TransferAmountLab;
@property (weak, nonatomic) IBOutlet UILabel *TransferAmountValueLab;
@property (weak, nonatomic) IBOutlet UIButton *selectBtn;
@property (weak, nonatomic) IBOutlet ClickButton *makeSureBtn;
@property (weak, nonatomic) IBOutlet UILabel *textLabel;
@property (weak, nonatomic) IBOutlet UIButton *unselectBtn;
@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) NSInteger     requestType;
@property (nonatomic, assign) BOOL          isLoading;
@end

@implementation MakeSureToViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];
    [self initData];
}
#pragma mark - initView
- (void)initView{
    [self initNavBarTitle:@"转入确认" andLeftItemName:@"返回" andRightItemName:@""];
    self.view.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1.0];
    self.makeSure_name.font = KFontSize(13);
    self.makeSure_nameValue.font = KFontSize(12);
    self.makeSure_time.font = KFontSize(13);
    self.makeSure_timeValue.font = KFontSize(12);
    self.makeSure_payStyle.font = KFontSize(13);
    self.bankNumLab.font = KFontSize(11);
    self.bankStyleLab.font = KFontSize(12);
    self.TransferAmountLab.font = KFontSize(13);
    self.TransferAmountValueLab.font = KFontSize(12);
    self.makeSureBtn.layer.masksToBounds = YES;
    self.makeSureBtn.layer.cornerRadius = 5;
    self.textLabel.font = KFontSize(10);
    if (self.viewType == 2) {
        
    }
    NSString *mindStr = [NSString stringWithFormat:@"%@",@"本人已阅读《借款协议书()》,并已完全理解、接受和同意签署上述文件的全部内容.本人的投资决策完全基于本人的独立自主判断做出,并自愿承担投资该项目所产生的相关风险和后果."];
    
    CGFloat mindHeight = [MyTools getSizeOfString:mindStr maxWidth:MSWIDTH - 20 maxHeight:1000 withFontSize:10].height;
    CGRect frame = self.textLabel.frame;
    if (IS_iPhone5) {
        frame.size.height = mindHeight+KAdaptNum(30);
    }else if (IS_iPhone6){
    
      frame.size.height = mindHeight+KAdaptNum(15);
    }else{
      frame.size.height = mindHeight-3;
    }
    
    self.textLabel.frame = frame;
    //通过字符串标记
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:mindStr];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:10] range:NSMakeRange(0, attributedString.length)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(5, 9)];
    _textLabel.attributedText = attributedString;
    [_textLabel addAttributeActionWithStrings:@[@"《借款协议书()》"] tapTargetAction:^(NSString *string, NSRange range, NSInteger index) {
        NSLog(@"点击字符串:%@ 范围在%@，第%ld个",string,NSStringFromRange(range),index+1);
    }];
  
}
#pragma mark - Data
-(void)initData{
  
    if (_viewType == 1) {
        _makeSure_payStyle.text = @"网银转入";
        [self getBanksDict];
    }else{
        _makeSure_payStyle.text = @"余额转入";
        _payStyleImageView.image = [UIImage imageNamed:@"turnout_balance"];
        _bankStyleLab.text = @"账户余额";
        _bankNumLab.text  = _balance;
    }
    _TransferAmountValueLab.text = [NSString stringWithFormat:@"%@元",_amount];
}
- (void)transferedRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求,请稍候..."];
        return;
    }
    if (_rechargeAppType == 2) { //富友
        _requestType = 4;
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:@"525" forKey:@"OPT"];
        [parameters setObject:@"" forKey:@"body"];
        [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
        [parameters setObject:@"2" forKey:@"type"];
        [parameters setObject:[NSString stringWithFormat:@"%@",_amount] forKey:@"amount"];
       
        if (_requestClient == nil) {
            _requestClient = [[NetWorkClient alloc] init];
            _requestClient.delegate = self;
        }
        [_requestClient requestGet:@"app/services" withParameters:parameters];
    }else {  //畅捷
        _requestType = 1;
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        if (self.viewType == 1) {
            [parameters setObject:@"520" forKey:@"OPT"];
        }else {
            [parameters setObject:@"504" forKey:@"OPT"];
        }
        [parameters setObject:@"" forKey:@"body"];
        [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"userId"];
        //    NSString *password = [NSString encrypt3DES:_passwordTextField.text key:DESkey];
        //    [parameters setObject:password forKey:@"dealpwd"];
        [parameters setObject:[NSString stringWithFormat:@"%@",_amount] forKey:@"money"];
        
       
        if (_requestClient == nil) {
            _requestClient = [[NetWorkClient alloc] init];
            _requestClient.delegate = self;
        }
        [_requestClient requestGet:@"app/services" withParameters:parameters];
    }
    
}

- (void)startRequest {
    _isLoading = YES;
}

- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    NSDictionary *dics=(NSDictionary *)obj;
    DLOG(@"--%@",dics);
    
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        
        if (_requestType == 4) {
            
            
            NSString * myVERSION = [NSString stringWithFormat:@"2.0"] ;     //SDK 接口版本参数  定值
            NSString * myMCHNTCD = [NSString stringWithFormat:@"%@",dics[@"MCHNTCD"]]; // 商户号
            NSString * myMCHNTORDERID = [NSString stringWithFormat:@"%@",dics[@"MCHNTORDERID"]]; // 商户订单号
            NSString * myUSERID = [NSString stringWithFormat:@"%@",dics[@"USERID"]]; // 用户编号
            NSString * myAMT = [NSString stringWithFormat:@"%@",dics[@"AMT"]];  // 金额
            NSString * myBANKCARD = [NSString stringWithFormat:@"%@",dics[@"BANKCARD"]]; // 银行卡号
            NSString * myBACKURL = [NSString stringWithFormat:@"%@",dics[@"BACKURL"]]; // 回调地址
            
            NSString * myNAME = [NSString stringWithFormat:@"%@",dics[@"NAME"]] ; // 姓名
            NSString * myIDNO = [NSString stringWithFormat:@"%@",dics[@"IDNO"]] ; // 证件编号
            NSString * myIDTYPE = [NSString stringWithFormat:@"%@",dics[@"IDTYPE"]] ; // 证件类型(目前只支持身份证)
            NSString * myTYPE = [NSString stringWithFormat:@"%@",dics[@"TYPE"]] ;
            NSString * mySIGNTP = [NSString stringWithFormat:@"%@",dics[@"SIGNTP"]] ;
            NSString * myMCHNTCDKEY = [NSString stringWithFormat:@"%@",dics[@"MCHNTCDKEY"]] ;//商户秘钥
            
            
            //            NSString * mySIGN = [NSString stringWithFormat:@"%@|%@|%@|%@|%@|%@|%@|%@|%@|%@|%@|%@" , myTYPE,myVERSION,myMCHNTCD,myMCHNTORDERID,myUSERID,myAMT,myBANKCARD,myBACKURL,myNAME,myIDNO,myIDTYPE,myMCHNTCDKEY] ;
            NSString * mySIGN = [NSString stringWithFormat:@"%@",dics[@"SIGN"]];
            
            //mySIGN = [mySIGN MD5String] ;                         //签名字段
            
            //添加环境参数  BOOL 变量 @"TEST"   YES 是测试  NO     是生产。  使用生产环境时 ，请传入真实信息，并替换生产商户号和秘钥
            
            //富友提供测试用的生产环境商户号和秘钥 ： mchntcd : 0002900F0280321       key : fx45crzkmo8akn24plwvrv8ywd10zjuy
            //测试商户号和秘钥                    mchntcd : 0002900F0096235       key : 5old71wihg2tqjug9kkpxnhx9hiujoqj
            BOOL test = kIsTestEnvironment;
            NSNumber * testNumber = [NSNumber numberWithBool:test] ;
            NSDictionary * dicD = @{@"TYPE":myTYPE,@"VERSION":myVERSION,@"MCHNTCD":myMCHNTCD,@"MCHNTORDERID":myMCHNTORDERID,@"USERID":myUSERID,@"AMT":myAMT,@"BANKCARD":myBANKCARD,@"BACKURL":myBACKURL,@"NAME":myNAME,@"IDNO":myIDNO,@"IDTYPE":myIDTYPE,@"SIGNTP":mySIGNTP,@"SIGN":mySIGN , @"TEST" : testNumber} ;
            // NSLog(@"😄dicD =%@ " , dicD) ;
            
            if (dicD.count>0) {
                [self gotoFuYouPayWithDic:dicD];
            }
            
            
            }else if (_requestType == 1) {
            if (self.viewType == 2) {
                [SVProgressHUD showSuccessWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
               
                    [self transferresSuccess];
                
            }else {
                
                if (dics[@"resultReturn"] && ![dics[@"resultReturn"] isKindOfClass:[NSNull class]]) {
                    NSDictionary *resultReturn = dics[@"resultReturn"];
                    
                    if ((resultReturn[@"flag"]&&![resultReturn[@"flag"] isKindOfClass:[NSNull class]]) && (resultReturn[@"outer_trade_no"]&&![resultReturn[@"outer_trade_no"] isKindOfClass:[NSNull class]]) && (resultReturn[@"uuid"]&&![resultReturn[@"uuid"] isKindOfClass:[NSNull class]])) {
                        
                        BOOL flag = [resultReturn[@"flag"] boolValue];
                        NSString *outer_trade_no = [NSString stringWithFormat:@"%@",resultReturn[@"outer_trade_no"]];
                        NSString *uuid = [NSString stringWithFormat:@"%@",resultReturn[@"uuid"]];
                        if (flag && outer_trade_no.length>0 && uuid.length>0) {
                            [SVProgressHUD dismiss];
                            RechargeVerifyViewController *verify = [[RechargeVerifyViewController alloc] init];
                            verify.uuidStr = uuid;
                            verify.tradeNoStr = outer_trade_no;
                            [self.navigationController pushViewController:verify animated:YES];
                            
                        }else {
                            NSString *str = [dics objectForKey:@"retMsg"];
                            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                            [alert show];
                        }
                    }else {
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"参数有误!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [alert show];
                    }
                }else {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"参数有误!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                    [alert show];
                }
                /*
                 if ([[dics objectForKey:@"retCode"] isEqualToString:@"0000"]) {
                 if (self.delegate && [self.delegate respondsToSelector:@selector(gotoBaofoPayWithTradeNo:)]) {
                 [self.delegate gotoBaofoPayWithTradeNo:[dics objectForKey:@"tradeNo"]];
                 }
                 }
                 else {
                 NSString*str = [dics objectForKey:@"retMsg"];
                 if (!str) {
                 str = @"创建订单号失败";
                 }
                 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                 [alert show];
                 }*/
                
            }
        }
        
        
    }else {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
    }
}



- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    _isLoading = NO;
    
}

- (void) networkError {
    _isLoading = NO;
    
}

- (void)gotoFuYouPayWithDic:(NSDictionary *)dic {
#if TARGET_IPHONE_SIMULATOR
    [SVProgressHUD showErrorWithStatus:@"亲，模拟器不可运行哦~"];
    
#elif TARGET_OS_IPHONE
    FUMobilePay * pay = [FUMobilePay shareInstance];
    if([pay respondsToSelector:@selector(mobilePay:delegate:)])
        [pay performSelector:@selector(mobilePay:delegate:) withObject:dic withObject:self];
    
#endif
    
}

#pragma mark ------支付结果回调------
- (void)payCallBack:(BOOL)success responseParams:(NSDictionary *)responseParams
{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:responseParams[@"RESPONSEMSG"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil] ;
    if (success) {
        alert.tag = 12;
    }
    [alert show] ;
}

- (void)transferresSuccess {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"sqbBalanceChange" object:nil];
    
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 3] animated:YES];
}
#pragma mark -Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag==12 && buttonIndex==0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sqbBalanceChange" object:nil];
        [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 3] animated:YES];
     }else if (alertView.tag == 13 && buttonIndex == 0){
        
        [self.navigationController popViewControllerAnimated:YES];
     }
    
    
}

#pragma mark - Action
- (void)back {
    
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"确认要取消该笔投资吗?" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil] ;
    alert.tag = 13;
    [alert show] ;
}

- (IBAction)clickMakeSure:(id)sender {
    if (!self.selectBtn.hidden) {
        
        if(self.fy_onoff == 0 && self.cj_onoff == 0 && self.viewType == 1){
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"支付渠道正在维护中,详情请查看最新相关公告,给您带来不便，敬请谅解。" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            alertView.tag = 222;
            [alertView show];
            return;
        }else{
            if (_viewType == 1) {
                
                [AppDelegateInstance.window addSubview:self.payView];
                
            }else if(_viewType == 2){
                
                [self transferedRequest];
            }
            
            
        }
        if (self.viewType == 1) {
            
            [AppDelegateInstance.window addSubview:self.payView];
            }else if(self.viewType == 2){
            
            [self transferedRequest];
            }
       
        
    }else{
        [SVProgressHUD showErrorWithStatus:@"请勾选上方借款协议书!"];
    }
}

- (IBAction)clickSelect:(id)sender {
    self.selectBtn.hidden = NO;
}
- (IBAction)clickUnselect:(id)sender {
     self.selectBtn.hidden = YES;
}
// 畅捷支付
- (void)cjPayButtonClick:(UIButton *)sender {
    _rechargeAppType = 1;
    [self.payView cancelView];
    
    [SVProgressHUD showWithStatus:@"正在下单"];
    
    [self transferedRequest];
}


// 富友支付
- (void)fyPayButtonClick:(id)sender {
    
    _rechargeAppType = 2;
    [self.payView cancelView];
    [self transferedRequest];
}


- (void)getBanksDict {
    
    if (_userBanksDict) {
        NSString *bankNameStr = [NSString stringWithFormat:@"%@",_userBanksDict[@"bankName"]];
        bankNameStr = [CommonClass setBankLogoImageWithBankName:bankNameStr imageView:_payStyleImageView];
        _bankStyleLab.text = bankNameStr;
        NSString *bankNumStr = [NSString stringWithFormat:@"%@",_userBanksDict[@"account"]];
        _bankNumLab.text = [NSString stringWithFormat:@"尾号%@",[bankNumStr substringFromIndex:bankNumStr.length-4]];
        
    }else {
        
    }
    
}
// 充值类型
- (payTypeView *)payView{
    if (_payView == nil) {
        _payView = [[payTypeView alloc] init];
        _payView.frame = [UIScreen mainScreen].bounds;
        [_payView.cjBtn addTarget:self action:@selector(cjPayButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_payView.fyBtn addTarget:self action:@selector(fyPayButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _payView;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
